﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint.WebControls;
using SlamCms.SharePoint.UserManagement.Data;
using System.Data.EntityClient;
using Slam;
using Slam.Configuration;
using Microsoft.SharePoint;
using SlamCms.SharePoint.Data;
using System.Xml.Linq;
using System.Data.Linq;
using System.Linq;
using System.Collections.Generic;
using SlamCms.SharePoint.Core;
using System.Web;
using SlamCms.Configuration;
using Slam.FieldTypes;
using System.Reflection;

namespace SlamCms.SharePoint.FieldTypes
{
	[SlamFieldAction]
	public partial class CKEditorFieldControl : SlamFieldControl
	{
        protected CKEditor.NET.CKEditorControl ckEditor;

		public string ConfigFileName
		{
			get;
			set;
		}

		public string DocumentUploadPath
		{
			get;
			set;
		}

		public string ImageUploadPath
		{
			get;
			set;
		}

		public override object Value
		{
			get
			{
				this.EnsureChildControls();
				return this.ckEditor.Text;
			}
            set 
            {
                this.EnsureChildControls();
                this.ckEditor.Text = Convert.ToString(value);
            }
		}

		protected override string DefaultTemplateName
		{
			get
			{
                return "SlamCMSCKEditorFieldControl";
			}
		}

		protected override void CreateChildControls()
		{
			if (Field == null)
				return;

			base.CreateChildControls();

			if (ControlMode == SPControlMode.Display)
				return;

			if (!base.IsFieldValueCached)
			{
				ckEditor = (CKEditor.NET.CKEditorControl)TemplateContainer.FindControl("ckEditor");
				if (!String.IsNullOrEmpty(DocumentUploadPath))
				{	
					ckEditor.FilebrowserBrowseUrl = GetEditorBasePath() + "/filemanager/index.html?path=" + HttpUtility.UrlEncode(DocumentUploadPath).Replace("+", "%20");
				}
				if (!String.IsNullOrEmpty(ImageUploadPath))
				{	
					ckEditor.FilebrowserImageBrowseUrl = GetEditorBasePath() + "/filemanager/index.html?type=Images&path=" + HttpUtility.UrlEncode(ImageUploadPath).Replace("+", "%20");
				}
				if (!String.IsNullOrEmpty(ConfigFileName))
				{
					ckEditor.CustomConfig = ConfigFileName;
				}
				ckEditor.BasePath = GetEditorBasePath();
				if (ItemFieldValue != null)
					ckEditor.Text = ItemFieldValue.ToString();
			}
		}

        private string GetEditorBasePath()
        {
            AssemblyName assemblyName = Assembly.GetExecutingAssembly().GetName();
            return "/_wpresources/"+(assemblyName.Name + "/" + assemblyName.Version.ToString() + "__" + BitConverter.ToString(assemblyName.GetPublicKeyToken()).Replace("-", String.Empty)+"/ckeditor");
        }
	}
}
